﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Text;
using System.IO;
using System.Xml;
using System.Linq;

using System.Windows.Browser;
using System.Threading;
using System.Windows.Data;

namespace tianya
{
    public class RequestState
    {
        // This class stores the State of the request.
        const int BUFFER_SIZE = 1024;
        public StringBuilder requestData;
        public byte[] BufferRead;
        public HttpWebRequest request;
        public HttpWebResponse response;
        public Stream streamResponse;

        public RequestState()
        {
            BufferRead = new byte[BUFFER_SIZE];
            requestData = new StringBuilder("");
            request = null;
            streamResponse = null;
        }
    }

    public partial class MainPage : UserControl
    {
        
        

        string result="";
        public static System.Threading.ManualResetEvent allDone = null;
        const int BUFFER_SIZE = 1024;
        public MainPage()
        {
            InitializeComponent();
            Page_Load();
        }
        OAuthBase oAuth = new OAuthBase();
        string apiKey = "810a487c55c8a2b7e20500410663637d04f4a3385";//申请的App Key
        string apiKeySecret = "7c02f91c6ac31a7ec20f6b3041916bfc";//申请的App Secret
        string requestTokenUri = "http://open.tianya.cn/oauth/request_token.php";
        string AUTHORIZE = "http://open.tianya.cn/oauth/authorize.php";
        string ACCESS_TOKEN = "http://open.tianya.cn/oauth/access_token.php";
        string oauth_token = "";
        string oauth_token_secret = "";

        protected void Page_Load()
        {
           
            if (HtmlPage.Document.QueryString.Keys.Contains("oauth_token")) 
            oauth_token = HtmlPage.Document.QueryString["oauth_token"];

            if (HtmlPage.Document.QueryString.Keys.Contains("oauth_token_secret"))
            {
                CookiesUtils.SetCookie("oauth_token_secret", HtmlPage.Document.QueryString["oauth_token_secret"]);
                oauth_token_secret = HtmlPage.Document.QueryString["oauth_token_secret"];
            }
            if (HtmlPage.Document.QueryString.Keys.Contains("oauth_verifier"))
            {
                CookiesUtils.SetCookie("oauth_verifier", HtmlPage.Document.QueryString["oauth_verifier"]);

                getAccessToken(oauth_token, CookiesUtils.GetCookie("oauth_verifier"));
            }


            if (!string.IsNullOrEmpty(oauth_token) && !string.IsNullOrEmpty(oauth_token_secret))
                HtmlPage.Window.Navigate(new Uri(AUTHORIZE + "?oauth_token=" + oauth_token + "&" + "consumer_key=" + apiKey + "&"
                    + "oauth_callback=" + oAuth.UrlEncode("http://localhost:57923/tianyaTestPage.aspx")));
            

            //if (!string.IsNullOrEmpty(Request["oauth_verifier"]))
            //{
            //getAccessToken(Request["oauth_token"].ToString(), Request["oauth_verifier"].ToString());
            //}
            //else {
            ////Button1.Visible = true;
            //}

        }

        public void getRequestToken()
        {
            StringBuilder sbRequestToken = new StringBuilder();

            sbRequestToken.AppendFormat("?oauth_consumer_key={0}&", apiKey);
            sbRequestToken.AppendFormat("oauth_nonce={0}&", oAuth.GenerateNonce());
            sbRequestToken.AppendFormat("oauth_signature_method={0}&", "HMAC-SHA1");
            sbRequestToken.AppendFormat("oauth_timestamp={0}&", oAuth.GenerateTimeStamp());
            sbRequestToken.AppendFormat("oauth_version={0}", "1.0");
            string strRequestToken = requestTokenUri + sbRequestToken.ToString();
            Uri uri = new Uri(strRequestToken);
            string nonce = oAuth.GenerateNonce();
            string timeStamp = oAuth.GenerateTimeStamp();
            string normalizeUrl, normalizedRequestParameters;

            // 签名
            string sig = oAuth.GenerateSignature(
            uri,
            apiKey,
            apiKeySecret,
            string.Empty,
            string.Empty,
            "Get",
            timeStamp,
            nonce,
            OAuthBase.SignatureTypes.HMACSHA1,
            string.Empty,
            out normalizeUrl,
            out normalizedRequestParameters);
            sig = HttpUtility.UrlEncode(sig);

            //构造请求Request Token的url
            StringBuilder sb = new StringBuilder(requestTokenUri.ToString());
            sb.AppendFormat("?oauth_consumer_key={0}&", apiKey);
            sb.AppendFormat("oauth_nonce={0}&", nonce);
            sb.AppendFormat("oauth_signature_method={0}&", "HMAC-SHA1");
            sb.AppendFormat("oauth_timestamp={0}&", timeStamp);
            sb.AppendFormat("oauth_version={0}&", "1.0");
            sb.AppendFormat("oauth_signature={0}", sig);

            //Console.WriteLine("请求Request Token的url: \n" + sb.ToString());
           
            //请求Request Token
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(sb.ToString());
            RequestState myRequestState = new RequestState();
            myRequestState.request = request;
            IAsyncResult result = (IAsyncResult)request.BeginGetResponse(new AsyncCallback(RespCallback), myRequestState);

            // HttpWebResponse response = (System.Net.HttpWebRequest)request.GetResponse();
            //StreamReader stream = new StreamReader(response.GetResponseStream(), System.Text.Encoding.UTF8);
            //string responseBody = stream.ReadToEnd();
            //stream.Close();
            //response.Close();
            //int intOTS= responseBody.IndexOf("oauth_token=");
            //int intOTSS = responseBody.IndexOf("&oauth_token_secret=");
            //SessionManager.Session["oauth_token"] = responseBody.Substring(intOTS + 12, intOTSS-(intOTS + 12));
            //SessionManager.Session["oauth_token_secret"] = responseBody.Substring((intOTSS + 20), responseBody.Length – (intOTSS + 20));
            //Response.Redirect(AUTHORIZE + "?oauth_token=" + Session["oauth_token"] + "&oauth_callback=http://me.tianya.cn/oauth/test/callback.php");
        }
        private void RespCallback(IAsyncResult asynchronousResult)
        {
            try
            {
                // State of request is asynchronous.
                RequestState myRequestState = (RequestState)asynchronousResult.AsyncState;
                HttpWebRequest myHttpWebRequest2 = myRequestState.request;
                myRequestState.response = (HttpWebResponse)myHttpWebRequest2.EndGetResponse(asynchronousResult);

                // Read the response into a Stream object.
                Stream responseStream = myRequestState.response.GetResponseStream();
                myRequestState.streamResponse = responseStream;

                // Begin the Reading of the contents of the HTML page and print it to the console.
                IAsyncResult asynchronousInputRead = responseStream.BeginRead(myRequestState.BufferRead, 0, BUFFER_SIZE, new AsyncCallback(ReadCallBack), myRequestState);
            }
            catch (Exception e)
            {
                // Need to handle the exception
            }
        }
        public void UseAccessToken(string AccessToken, string AccessToken_Secret)
        {

            string prefix = "http://open.tianya.cn/api/bbs/getitemlist.php";
            string URL = string.Format(prefix+"?appkey={0}&oauth_token={1}&oauth_token_secret={2}&timestamp={3}&tempkey={4}&outformat=xml",

            apiKey, AccessToken, AccessToken_Secret, oAuth.GenerateTimeStamp(), "");

           // HtmlPage.Window.Navigate(new Uri(URL));

            WebRequestHelper _webRequestHelper = new WebRequestHelper();
            _webRequestHelper.SendRequest(URL);
            _webRequestHelper.OnResultEvent += new WebRequestHelper.OnResultEventHandler(_webRequestHelper_OnResultEvent);
        
        }

        void _webRequestHelper_OnResultEvent(object sender, OnResultEventArgs e)
        {
            
            Dispatcher.BeginInvoke(() =>
            {
                
               
            });
        }

        
        private   void ReadCallBack(IAsyncResult asyncResult)
        {
            try
            {

                RequestState myRequestState = (RequestState)asyncResult.AsyncState;
                Stream responseStream = myRequestState.streamResponse;
                int read = responseStream.EndRead(asyncResult);
                // Read the HTML page and then do something with it
                if (read > 0)
                {
                    myRequestState.requestData.Append(Encoding.UTF8.GetString(myRequestState.BufferRead, 0, read));
                    IAsyncResult asynchronousResult = responseStream.BeginRead(myRequestState.BufferRead, 0, BUFFER_SIZE, new AsyncCallback(ReadCallBack), myRequestState);
                }
                else
                {
                    if (myRequestState.requestData.Length > 1)
                    {
                        string stringContent;
                        stringContent = myRequestState.requestData.ToString();

                        result = stringContent;
                        if (result.IndexOf("oauth_callback_confirmed") > -1)

                            Dispatcher.BeginInvoke(() => { getAccessToken(result); });
                        else
                        {
                            string[] ReturnValues = result.Split('&');
                            Dictionary<string, string> TokenQuery = new Dictionary<string, string>();
                            foreach (string s in ReturnValues)
                            {
                                string[] QueryValue = s.Split('=');
                                TokenQuery.Add(QueryValue[0], QueryValue[1]);
                            }
                            Dispatcher.BeginInvoke(() => { UseAccessToken(TokenQuery["oauth_token"], TokenQuery["oauth_token_secret"]); });
                        }
                        // do something with the response stream here
                    }
                    
                    responseStream.Close();
                    allDone.Set();

                }

            }
            catch (WebException e)
            {
                // Need to handle the exception
            }

        }
        public void getAccessToken(string result)
        {
            result = "http://localhost:57923/tianyaTestPage.aspx?" + result;
            Uri ReturnResult = new Uri(result);




            HtmlPage.Window.Navigate(ReturnResult);
        
        }
        public void getAccessToken(string requestToken, string oauth_verifier)
        {
            Uri uri = new Uri(ACCESS_TOKEN);
            string nonce = oAuth.GenerateNonce();
            string timeStamp = oAuth.GenerateTimeStamp();
            string normalizeUrl, normalizedRequestParameters;

            // 签名
            string sig = oAuth.GenerateSignature(
            uri,
            apiKey,
            apiKeySecret,
            requestToken,
            CookiesUtils.GetCookie("oauth_token_secret"),
            "Get",
            timeStamp,
            nonce,
            OAuthBase.SignatureTypes.HMACSHA1,
            oauth_verifier,
            out normalizeUrl,
            out normalizedRequestParameters);
            sig = HttpUtility.UrlEncode(sig);

            //构造请求Access Token的url
            StringBuilder sb = new StringBuilder(uri.ToString());
            sb.AppendFormat("?oauth_consumer_key={0}&", apiKey);
            sb.AppendFormat("oauth_nonce={0}&", nonce);
            sb.AppendFormat("oauth_timestamp={0}&", timeStamp);
            sb.AppendFormat("oauth_signature_method=HMAC-SHA1&");
            sb.AppendFormat("oauth_version={0}&", "1.0");
            sb.AppendFormat("oauth_signature={0}&", sig);
            sb.AppendFormat("oauth_token={0}&", requestToken);
            sb.AppendFormat("oauth_verifier={0}", oauth_verifier);


            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(sb.ToString());
            RequestState myRequestState = new RequestState();
            myRequestState.request = request;
            IAsyncResult result = (IAsyncResult)request.BeginGetResponse(new AsyncCallback(RespCallback), myRequestState);

            //请求Access Token
            //HttpWebRequest request = (HttpWebRequest)WebRequest.Create(sb.ToString());
            //HttpWebResponse response = (System.Net.HttpWebResponse)request.GetResponse();
            //StreamReader stream = new StreamReader(response.GetResponseStream(), System.Text.Encoding.UTF8);
            //string responseBody = stream.ReadToEnd();
            //stream.Close();
            //response.Close();
            //int intOTS = responseBody.IndexOf("oauth_token=");
            //int intOTSS = responseBody.IndexOf("&oauth_token_secret=");
            //int intUser = responseBody.IndexOf("&user_id=");
            //Session["oauth_token"] = responseBody.Substring(intOTS + 12, intOTSS – (intOTS + 12));
            //Session["oauth_token_secret"] = responseBody.Substring((intOTSS + 20), intUser – (intOTSS + 20));
            //Session["User_Id"] = responseBody.Substring((intUser + 9), responseBody.Length – (intUser + 9));
           // verify_credentials();
        }

        public void verify_credentials()
        {
            Uri uri = new Uri("http://api.t.sina.com.cn/account/verify_credentials.xml");

            string nonce = oAuth.GenerateNonce();
            string timeStamp = oAuth.GenerateTimeStamp();
            string normalizeUrl, normalizedRequestParameters;

            // 签名
            string sig = oAuth.GenerateSignature(
            uri,
            apiKey,
            apiKeySecret,
            CookiesUtils.GetCookie("oauth_token"),
            CookiesUtils.GetCookie("oauth_token_secret"),
            "Get",
            timeStamp,
            nonce,
            OAuthBase.SignatureTypes.HMACSHA1,
            string.Empty, //oauth_verifier,
            out normalizeUrl,
            out normalizedRequestParameters);
            sig = HttpUtility.UrlEncode(sig);

            StringBuilder sb = new StringBuilder(uri.ToString());
            sb.AppendFormat("?oauth_consumer_key={0}&", apiKey);
            sb.AppendFormat("oauth_nonce={0}&", nonce);
            sb.AppendFormat("oauth_timestamp={0}&", timeStamp);
            sb.AppendFormat("oauth_signature_method=HMAC-SHA1&");
            sb.AppendFormat("oauth_version={0}&", "1.0a");
            sb.AppendFormat("oauth_signature={0}&", sig);
            sb.AppendFormat("oauth_token={0}&", CookiesUtils.GetCookie("oauth_token"));
            
            //HttpWebRequest request = (HttpWebRequest)WebRequest.Create(sb.ToString());
            //HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            //StreamReader stream = new StreamReader(response.GetResponseStream(), System.Text.Encoding.UTF8);
            //string responseBody = stream.ReadToEnd();
            //stream.Close();
            //response.Close();
            //Response.Write("验证成功！！");
        }



        private void button1_Click(object sender, RoutedEventArgs e)
        {
            
            allDone = new ManualResetEvent(false);
            getRequestToken();
            
        }
    }
}
